package com.example.dql.diary.PictureSelection;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.dql.diary.Model.PicDTO;
import com.example.dql.diary.R;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.functions.Action1;

public class SelectPicActivity extends AppCompatActivity implements BaseQuickAdapter.OnItemChildClickListener,BaseQuickAdapter.OnItemClickListener{
    private static final int REQUEST_CODE_CHOOSE = 23;//定义请求码常量
    private static final int REQUEST_CODE_LOOKPIC = 10;
    private static final int REQUEST_CODE_BACKLOOKPIC = 14;

    private static final int REQUEST_CAMERA = 22;
    private RecyclerView recyclerView;
    private PicAdapter adapter;
    private List<PicDTO> mPicList = new ArrayList<>();
    private List<String> mPhotoList = new ArrayList<>();
    private List<Uri> mRequsetList = new ArrayList<>();
    private Button button;
    private File file;
    private ImageView buttonBack;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.btn_start);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        buttonBack = (ImageView)findViewById(R.id.button_back);
        buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        askPermission();//权限申请
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));
        adapter = new PicAdapter(null);
        mPicList.add(new PicDTO(null,true));
        adapter.addData(mPicList);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);

    }

    private void ChoosePic() {
        Matisse.from(SelectPicActivity.this)
                .choose(MimeType.allOf())
                .countable(true)
                .theme(R.style.Matisse_Dracula)
                .maxSelectable(9-mPicList.size())
                .capture(true)
                .captureStrategy(new CaptureStrategy(true,"com.example.dql.diary"))//存储到哪里
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new MyGlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);

    }

    private void askPermission() {
        RxPermissions.getInstance(SelectPicActivity.this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_PHONE_STATE)//多个权限用","隔开
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            //当所有权限都允许之后，返回true
                            Log.i("permissions", "btn_more_sametime：" + aBoolean);
                        } else {
                            //只要有一个权限禁止，返回false，
                            //下一次申请只申请没通过申请的权限
                            Log.i("permissions", "btn_more_sametime：" + aBoolean);
                        }
                    }
                });

/*        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxPermissions.getInstance(SelectPicActivity.this)
                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA)//多个权限用","隔开
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {
                                    //当所有权限都允许之后，返回true
                                    Log.i("permissions", "btn_more_sametime：" + aBoolean);
                                } else {
                                    //只要有一个权限禁止，返回false，
                                    //下一次申请只申请没通过申请的权限
                                    Log.i("permissions", "btn_more_sametime：" + aBoolean);
                                }
                            }
                        });

            }
        });*/
    }

    List<Uri> mSelected;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);//选择的图片
            Log.d("Matisse", "mSelected: " + mSelected);
            adapter.setNewData(null);
            initImgList();
            if (( mPicList.size())< 9 ){
                mPicList.add(new PicDTO(null,true));
            }
            adapter.addData(mPicList);
        }
       else if (requestCode == REQUEST_CODE_LOOKPIC && resultCode == REQUEST_CODE_BACKLOOKPIC){
           mPhotoList = data.getStringArrayListExtra("requestList");
           initResultPic();
        }
        else if (requestCode == REQUEST_CAMERA){
            Toast.makeText(SelectPicActivity.this,"fuck",Toast.LENGTH_SHORT).show();
            Log.e("TAG", "---------" + FileProvider.getUriForFile(this, "com.example.dql.diary", file));
            adapter.setNewData(null);
            PicDTO a = new PicDTO( FileProvider.getUriForFile(this, "com.example.dql.diary", file),false);
            mPicList.add(a);
            mPhotoList.add(FileProvider.getUriForFile(this, "com.example.dql.diary", file).toString());
            if (( mPhotoList.size())< 9 ){
                mPicList.add(new PicDTO(null,true));
            }
            adapter.addData(mPicList);
        }
    }


    private void initImgList() {
        for(int i = 0 ;i < mSelected.size() ;i++){
            PicDTO a = new PicDTO(mSelected.get(i),false);
            mPicList.add(a);
            mPhotoList.add(mSelected.get(i).toString());
            Log.d("mPicList", mPicList.get(i).toString());
        }
    }


    //加载回调图片
    private void initResultPic() {
        mRequsetList.clear();
        for (int i =0 ;i<mPhotoList.size();i++){
            Uri uri = Uri.parse(mPhotoList.get(i));
            mRequsetList.add(uri);
        }
        adapter.setNewData(null);
        mPicList.clear();
        for(int i = 0 ;i < mPhotoList.size() ;i++){
            PicDTO a = new PicDTO(mRequsetList.get(i),false);
            mPicList.add(a);
            Log.d("mPicList", mPicList.get(i).toString());
        }
        if (( mPhotoList.size())< 9 ){
            mPicList.add(new PicDTO(null,true));
        }
        adapter.addData(mPicList);


    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()){
            case R.id.iv_add:
                if (mPicList.size()==1){
                    mPicList.remove(0);
                }else if (mPicList.size()==0){
                    mPicList.add(new PicDTO(null,true));
                    mPicList.remove(0);
                } else {
                    mPicList.remove(mPicList.size()-1);
                }
//                ChoosePic();
                showDialog();


                break;
        }
    }

    private void showDialog() {
        String[] items = new String[]{"拍照", "从相册选择"};
        new QMUIDialog.MenuDialogBuilder(SelectPicActivity.this)
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (i == 0){
                            takePhoto();
                        }else if (i == 1){
                            ChoosePic();
                        }
                        dialogInterface.dismiss();
                    }

                }).show();
    }

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)
                + imageFileName +".jpg");
        file.getParentFile().mkdirs();

        //改变Uri  注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.example.dql.diary", file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        startActivityForResult(new Intent(SelectPicActivity.this,LookPicActivity.class)
                .putStringArrayListExtra("imgList", (ArrayList<String>) mPhotoList).putExtra("position",String.valueOf(position)),REQUEST_CODE_LOOKPIC);
    }
}
